package com.hywood.app.live.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
@CrossOrigin("*")
@Controller
public class FileUploadService {
    @Value("${upload.url}")
    private String URL ;

    @RequestMapping(value = "/fileupload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return "文件上传失败";
        }
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filePath = "/var/www/html/upload/";
        String fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return URL + fileName;
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}
